<template xmlns:v-clipboard="http://www.w3.org/1999/xhtml">
  <div>
    <newHeader/>

    <!-- S 轮播模块 -->
    <swiperComponent/>
    <!-- E 轮播模块 -->

    <div class="m-content wrapbox clearfix">
      <div class="m-centbar">
        <h1>{{detais.title}}</h1>
        <div class="txtcont">
          <span class="time">{{detais.infopubldate}}</span>
          <div class="action" v-if="articleAction">
            <action-list
              :action="articleAction"
              @like="toggleLike"
              @message=""
              @collect="onCollect"
              @transmit="onTransmit"
              @share="onShare">
            </action-list>

          </div>

        </div>
        <div class="artcont" v-html="htmlDecodeByRegExp(detais.contentLab)">
        </div>
      </div>

      <div class="comments" v-if="newComment && newComment.show">
        <div class="new-comment">
          <post-comment
            :show="newComment.show"
            :textarea="newComment.textarea"
            :btn="newComment.btn"
            :content="newComment.content"
            @post-comment="submitComment">
          </post-comment>
        </div>
        <div class="comment-list" v-if="comments && comments.length">
          <ul>
            <li class="comment-item" v-for="(item, index) in comments" :key="index">
              <comment
                :comment="item"
                :replies="item.replies"
                @like="onLike"
                @report-comment="onReportComment"
                @delete-comment="onDeleteComment"
                @post-comment-reply="onPostCommentReply"
                @report-reply="onReportReply"
                @post-reply-reply="onPostReplyReply"
                @delete-reply="onDeleteReply">
              </comment>
            </li>
          </ul>
        </div>
        <div class="more-comments" v-if="detais.nextCommentPage && moreCommentBtn">
          <el-button type="text" :loading="moreCommentBtn.loading" @click="loadMoreComment">{{ moreCommentBtn.text ||
            '加载更多评论' }}
          </el-button>
        </div>
      </div>
      <!-- s 评论模块 -->
    </div>
    <el-dialog
      title="转发"
      :visible.sync="dialogVisible"
      width="30%">
      <el-input type="textarea" v-model="content"></el-input>
      <span slot="footer" class="dialog-footer">
    <el-button @click="dialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="ontransfer" :loading="loading">确 定</el-button>
  </span>
    </el-dialog>

    <bottom/>
  </div>
</template>
<script>
  import bottom from '@/components/Bottom'
  import newHeader from '@/components/NewHeader'
  import swiperComponent from '@/components/SSwiper'
  import {mapGetters} from 'vuex'
  import actionList from '@/components/action-list/index';
  import postComment from '@/components/post-comment/index';
  import comment from '@/components/comment/index';

  let STATUS = {
    notStart: '',
    doing: 'doing',
    done: 'done',
    fail: 'fail'
  };
  export default {
    data() {
      return {
        detais: '',
        comments: [],
        collectStatus: '',
        content: '',
        loading: false,
        dialogVisible: false,
        newComment: {
          show: true,
          textarea: {
            placeholder: '说点什么',
            autosize: {minRows: 3, maxRows: 10},
            type: 'textarea'
          },
          btn: {
            type: 'primary',
            loading: false,
            text: '发表评论'
          },
          content: ''
        },
        moreCommentBtn: {},
        isFirstLoadComment: true
      }
    },
    components: {
      bottom,
      newHeader,
      swiperComponent,
      actionList,
      postComment, comment,
    },
    mounted() {
      this.newId = this.$route.params.id //拿到通过路由传过来的ID
      this.getDetail(this.newId)
      this.$store.dispatch('updateHeadStatu', true)
      // this.loadMoreComment()
    },
    computed: {
      articleAction() {
        return {
          likeDone: this.detais.likeDone,
          likeCount: this.detais.likeCount,
          messageCount: this.detais.messageCount,
          shareCount: this.detais.shareCount,
          shareUrl: this.detais.shareUrl,
          shareTitle: this.detais.title,
          likeActionStatus: this.detais.likeActionStatus,
          collectStatus: this.detais.collectStatus,
          transmitStatus: this.detais.transmitStatus,
          collected: this.detais.collected,
        };
      }, ...mapGetters({
        userId: 'userId',
        username: 'username',
        photo: 'photo',
        isLogin: 'isLogin',
      })
    },
    watch: {
      'detais.postActionStatus'(newStatus, oldStatus) {
        if (newStatus === STATUS.done && oldStatus !== STATUS.done) {
          this.postCommentActionDone();
        }
      },
      'detais.loadActionStatus'(newStatus, oldStatus) {
        if (newStatus === STATUS.done && oldStatus !== STATUS.done) {
          if (this.moreCommentBtn) {
            this.moreCommentBtn.loading = false;
            this.moreCommentBtn.text = '';
          }
        }
      }
    },
    methods: {
     htmlDecodeByRegExp(str) {
        var s = "";
        if (str==undefined ||str.length == 0) return "";
        s = str.replace(/&amp;/g, "&");
        s = s.replace(/&lt;/g, "<");
        s = s.replace(/&gt;/g, ">");
        s = s.replace(/&nbsp;/g, " ");
        s = s.replace(/&#39;/g, "\'");
        s = s.replace(/&quot;/g, "\"");
        return s;
      },
      submitComment(comment) {
        if (!this.isLogin) {
          return;
        }
        if (this.detais.postActionStatus === STATUS.doing) {
          return;
        }
        this.newComment.content = comment;
        this.newComment.btn.loading = true;


        this.detais.postActionStatus = STATUS.doing;
        let params = {
          'conId': this.detais.id,
          'content': comment,
          'parentId': 0,
        }
        this.$post('/content/addContentComment', params).then(response => {
          this.$check(response)
          this.comments.unshift({
            user: {
              avatar: this.photo,
              nickname: this.username
            },
            id: response.data,
            text: comment,
            likeDone: false,
            likeCount: 0,
            likeActionStatus: '',
            postActionStatus: '',
            reportActionStatus: '',
            deleteActionStatus: '',
            canDelete: true,
            replies: []
          });
          this.detais.messageCount += 1;
          this.detais.postActionStatus = STATUS.done;
        })
      },
      postCommentActionDone() {
        let update = () => {
          this.newComment.btn.loading = false;
          this.newComment.content = '';
        };
        // 使用nextTick避免content 变化太快，使中间的数据变换被忽视
        this.$nextTick().then(update);
      },
      postNewComment() {
        if (this.isFirstLoadComment && this.article.nextCommentPage && this.article.loadActionStatus !== STATUS.doing) {
          this.isFirstLoadComment = false;
          this.loadMoreComment();
        }
        if (this.newComment) {
          if (!this.newComment.btn.loading) {
            this.newComment.show = !this.newComment.show;
          }
        } else {
          this.newComment = {
            show: true,
            textarea: {
              placeholder: '说点什么',
              autosize: {minRows: 3, maxRows: 10},
              type: 'textarea'
            },
            btn: {
              type: 'primary',
              loading: false,
              text: '发表评论'
            },
            content: ''
          };
        }
      },
      onCollect(comment, status) {
        if (this.collectStatus != STATUS.doing && !this.detais.collected) {
          this.collectStatus = STATUS.doing
          this.$post('/content/collectContent', {
            'conId': this.detais.id,
          }).then(response => {
            this.$check(response)
            this.$message.success('操作成功');
            this.detais.collected = true
            this.collectStatus = STATUS.done
          })
        }
      },
      ontransfer() {

        this.loading = true
        this.$post('/content/forwardContent', {
          'parentId': this.detais.id,
          'title': this.content,
        }).then(response => {
          this.$check(response)
          this.$message.success('操作成功');
          this.dialogVisible = false
          this.content = ''
          this.loading = false
        })
      },
      onTransmit(comment, status) {
        this.dialogVisible = true
      },
      onLike(comment, status) {

        this.detais.likeActionStatus = STATUS.doing;
        // TODO send like request
        let likeInd = 1
        if (comment.likeDone) {
          likeInd = 3
        } else {
          likeInd = 1
        }
        this.$post('/content/addContentLikesOrDislikes', {
          'id': comment.id,
          'likeInd': likeInd,
          'type': 1
        }).then(response => {
          this.$check(response)
          comment.likeDone = !comment.likeDone;
          if (comment.likeDone) {
            comment.likeCount += 1;
          } else {
            comment.likeCount -= 1;
          }
          this.$message.success('操作成功');
          comment.likeActionStatus = STATUS.done;

        })

      },
      onReportComment(comment, reportArgs) {
        comment.reportActionStatus = STATUS.doing
        this.$post('/content/addContentCommentTips', {
          'conId': this.detais.id,
          'commentId': comment.id,
          'content': reportArgs.text,
          'type': reportArgs.value,
          'userId': this.userId,
        }).then(response => {
          this.$check(response)
          this.$message.success('举报成功');
          comment.reportActionStatus = STATUS.done
        })
      },
      onDeleteComment(comment) {
        let commentFound = false;
        let count = 0;
        for (let item of this.comments) {
          if (item.id === comment.id) {
            commentFound = true;
            break;
          }
          count += 1;
        }
        if (commentFound) {
          this.$post('/content/delContentComment', {
            conId: this.detais.id,
            commentId: comment.id
          }).then(response => {
            this.$check(response)
            this.$message.success('删除评论成功');
            this.detais.messageCount -= (1 + comment.replies.length);
            this.comments.splice(count, 1);
          })
        }
      },
      onPostCommentReply(comment, reply) {
        comment.postActionStatus = STATUS.doing;
        let params = {
          'conId': this.detais.id,
          'content': reply,
          'parentId': comment.id,
        }
        this.$post('/content/addContentComment', params).then(response => {
          this.$check(response)
          comment.replies.unshift({
            user: {
              avatar: this.photo,
              nickname: this.username
            },
            id: response.data,
            text: reply,
            likeDone: false,
            likeCount: 0,
            likeActionStatus: '',
            postActionStatus: '',
            reportActionStatus: '',
            deleteActionStatus: '',
            canDelete: true,
            replies: []
          });
          comment.postActionStatus = STATUS.done;
          this.detais.messageCount += 1;
        })
      },
      onReportReply(reply, reportArgs) {
        reply.reportActionStatus = STATUS.doing
        this.$post('/content/addContentCommentTips', {
          'conId': this.detais.id,
          'commentId': reply.id,
          'content': reportArgs.text,
          'type': reportArgs.value,
          'userId': this.userId,
        }).then(response => {
          this.$check(response)
          this.$message.success('举报成功');
          reply.reportActionStatus = STATUS.done
        })


      },
      onDeleteReply(comment, reply) {
        let replyFound = false;
        let count = 0;
        for (let item of comment.replies) {
          if (item.id === reply.id) {
            replyFound = true;
            break;
          }
          count += 1;
        }
        if (replyFound) {
          this.$post('/content/delContentComment', {
            conId: this.detais.id,
            commentId: reply.id
          }).then(response => {
            this.$check(response)
            this.$message.success('删除评论成功');
            this.detais.messageCount -= 1;
            comment.replies.splice(count, 1);
          })
        }
      },
      onPostReplyReply(comment, reply, content) {
        this.$emit('post-reply-reply', this.article, comment, reply, content);
      },
      loadMoreComment() {
        // TODO send load comment request, setTimeout 只是为了模拟请求耗时

        let uuid = this.userId
        this.detais.loadActionStatus = STATUS.doing;

        this.$post('/content/queryContentCommentList', {
          condition: {
            'conId': this.detais.id,
            'userId': uuid,
          },
          current: this.detais.nextCommentPage,
          size: 5
        }).then(response => {
          this.$check(response)
          if (response.data != null) {
            let records = response.data.records

            for (var i = 0; i < records.length; i++) {

              let subComments = this.getComment(records[i].children, uuid)
              this.comments.push({
                user: {
                  avatar: records[i].businessData.photo,
                  nickname: records[i].businessData.nickName,
                },
                id: records[i].businessData.id,
                text: records[i].businessData.contentStr,
                likeDone: records[i].businessData.likeInd == 1,
                likeCount: records[i].businessData.likes,
                likeActionStatus: '',
                postActionStatus: '',
                reportActionStatus: '',
                deleteActionStatus: '',
                canDelete: records[i].businessData.userId = uuid,
                replies: subComments
              })
            }
            if (response.data.records.length == 5) {
              this.detais.nextCommentPage += 1;
            } else {
              this.detais.nextCommentPage = 0;
            }
          } else {
            this.detais.nextCommentPage = 0;
          }
          this.detais.loadActionStatus = STATUS.done;
        })
      }, getComment(records, uuid) {
        let list = []
        for (var i = 0; i < records.length; i++) {
          list.push({
            user: {
              avatar: records[i].businessData.photo,
              nickname: records[i].businessData.nickName,
            },
            id: records[i].businessData.id,
            text: records[i].businessData.contentStr,
            likeDone: records[i].businessData.likeInd == 1,
            likeCount: records[i].businessData.likes,
            likeActionStatus: '',
            postActionStatus: '',
            reportActionStatus: '',
            deleteActionStatus: '',
            canDelete: records[i].businessData.userId = uuid,
            replies: []
          })
        }
        // console.log(list)
        return list
      },
      toggleLike() {
        if (!this.isLogin) {
          return;
        }
        if (this.detais.likeActionStatus === STATUS.doing) {
          return;
        }

        this.detais.likeActionStatus = STATUS.doing;
        // TODO send like request
        let likeInd = 1
        if (this.detais.likeDone) {
          likeInd = 3
        } else {
          likeInd = 1
        }
        this.$post('/content/addContentLikesOrDislikes', {
          'id': this.detais.id,
          'likeInd': likeInd,
          'type': 1
        }).then(response => {
          this.$check(response)
          this.detais.likeDone = !this.detais.likeDone;
          if (this.detais.likeDone) {
            this.detais.likeCount += 1;
          } else {
            this.detais.likeCount -= 1;
          }
          this.$message.success('操作成功');
          this.detais.likeActionStatus = STATUS.done;
        })


      },
      onShare(type) {
        this.detais.shareCount += 1;
      },
      transfer(v) {
        let url = this.websideUrl
        // v.title = v.newsTitle
        v.time = v.infopubldate
        v.text = v.contentLab
        v.tags = v.tagList
        v.likeDone = v.likeInd == 1
        v.likeCount = v.likes
        v.messageCount = v.comments
        v.shareCount = v.shares
        v.comments = []
        v.likeActionStatus = ''
        v.postActionStatus = ''
        v.loadActionStatus = ''
        v.shareUrl = url + 'circleDetail/' + v.id
        v.routerUrl = '/circleDetail/' + v.id
        v.nextCommentPage = 1
        v.collectStatus = true
        v.transmitStatus = true
        v.collected = false
        return v

      },
      processList(data) {
        if (data.plates != null && data.plates != '') {
          var tagList = []
          var tags = v.plates.split(',')
          tags.forEach(function (n) {
            var tt = n.split(':')
            if (tt.length == 2) {
              var tag = {
                'id': tt[0],
                'name': tt[1]
              }
              tagList.push(tag)
            }
          }, this)
          data.tags = tagList
        }
      },
      getDetail(id) {
        let url = ''
        if (this.isLogin) {
          url = '/content/queryContentById?id=' + id + '&userId=' + this.userId
        } else {
          url = '/content/queryContentById?id=' + id
        }
        this.$fetch(url).then(response => {
          this.$check(response)
          // this.processList(response.data)
          this.detais = this.transfer(response.data)
          this.loadMoreComment()
        })
      },
    }
  }
</script>

<style scoped>
  .action {
    height: inherit;
    /*padding-top: 5px;*/
    float: right;
    font-size: 12px;
  }

  .comments {
    background: #fff;
    margin-top: 20px;
    padding: 30px 30px 30px;
  }

  .comment-item {
    border-bottom: 1px solid #ccc;
    padding-bottom: 20px;
  }

  .comment-item:last-child {
    border-bottom: none;
    padding-bottom: 0;
  }

  .more-comments {
    margin-top: 15px;
    text-align: center;
  }
</style>
